package com.huayun.plugin.pointcloud.fileparser;

import com.huayun.plugin.pointcloud.domain.Point;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class PointCloudFileParser {

    private final Logger log = LoggerFactory.getLogger(PointCloudFileParser.class);
    private String fileName;
    private File pcFile;

    public PointCloudFileParser(String fileName, File file) {
        this.fileName = fileName;
        this.pcFile = file;
    }

    public List<Point> ReadPCPoint() throws IOException {
        List<Point> result = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(this.pcFile)));

        // pcd点云
        if (this.fileName.toLowerCase().endsWith(".pcd")) {
            String line;
            boolean startFlag = false;
            while ((line = reader.readLine()) != null) {
                if(startFlag){
                    String[] lineValues = line.split(" ");
                    if (Arrays.stream(lineValues).count() >= 3) {
                        double pointX = Double.parseDouble(lineValues[0]);
                        double pointY = Double.parseDouble(lineValues[1]);
                        double pointZ = Double.parseDouble(lineValues[2]);
                        Point point = new Point(pointX, pointY, pointZ);
                        result.add(point);
                    }
                }

                if (line.startsWith("DATA")) {
                    startFlag = true;
                }
            }
        }

        // txt点云
        if (this.fileName.toLowerCase().endsWith(".txt")) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] lineValues = line.split(" ");
                if (Arrays.stream(lineValues).count() >= 3) {
                    double pointX = Double.parseDouble(lineValues[0]);
                    double pointY = Double.parseDouble(lineValues[1]);
                    double pointZ = Double.parseDouble(lineValues[2]);
                    Point point = new Point(pointX, pointY, pointZ);
                    result.add(point);
                }
            }
        }
        return result;
    }
}
